package com.yd.cfckc.util;

import sun.misc.BASE64Decoder;
import yd.ws.util.RC4;

import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author cuiyufeng
 * @email cuiyufeng1458@yundasys.com
 * @date 2020/10/16 2:31 下午
 */
public class StrFun {

    public StrFun() {
    }

    /**
     * �����ļ�
     *
     * @param location
     * @param content
     * @throws Exception
     */
    public static void saveFile(String location, String content)
            throws Exception {
        FileWriter fw = new FileWriter(location);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
        fw.close();
    }

    /**
     * ����shell
     *
     * @param cmd
     * @return
     * @throws IOException
     */
    public static String runCMD(String cmd) throws IOException {
        Runtime run = Runtime.getRuntime();
        Process p = run.exec(cmd);
        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = br.readLine()) != null) {
            sb.append(s);
            sb.append("\n");
        }
        p.getInputStream().close();
        p.getErrorStream().close();
        p.getOutputStream().close();
        return sb.toString();
    }

    /**
     * �ٶ�Զ��readline
     *
     * @param location
     * @return
     * @throws Exception
     */
    public static String readFile(String location) throws Exception {
        File file = new File(location);
        FileInputStream in = new FileInputStream(file);
        byte[] buf = new byte[(int) file.length()];
        in.read(buf);
        in.close();
        String s = new String(buf);
        return s;
    }

    public static String readFileUTF8(String location) throws Exception {
        File file = new File(location);
        FileInputStream in = new FileInputStream(file);
        byte[] buf = new byte[(int) file.length()];
        in.read(buf);
        in.close();
        String s = new String(buf,"UTF-8");
        return s;
    }

    /**
     * ���뷶Χ�������ļ�����
     * @param file
     * @param range
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String readFileWithRange(String file, String range)
            throws FileNotFoundException, IOException {
        int from = Integer.parseInt(range.substring(0, range.indexOf(',')));
        int to = Integer.parseInt(range.substring(range.indexOf(',') + 1));
        int iIndex = 0;
        FileReader reader = new FileReader(file);
        BufferedReader br = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String s = "";
        while ((s = br.readLine()) != null) {
            if (s.startsWith("<o")) {
                iIndex++;
                if (iIndex >= from && iIndex <= to) {
                    sb.append(s).append("\n");
                }
            }
        }
        sb.append("</data>");
        br.close();
        reader.close();
        s = "<data range=\"" + range + "/" + iIndex + "\">\n" + sb.toString();
        return s;
    }

    /**
     * ���MD5��
     *
     * @param s
     * @return
     * @throws Exception
     */
    public static String MD5(String s) throws Exception {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] buf = s.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(buf);
            byte[] md = md5.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ���MD6��
     *
     * @param s
     * @return
     * @throws Exception
     */
    public static String MD6(String s) throws Exception {
        //char hexDigits[]={ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        char hexDigits[] = { 'a', 'b', 'c', 'd', 'h', 'i', 'j', 'k', 'o', 'p', 'q', 'u', 'v', 'x', 'y', 'z' };
        try {
            byte[] buf = s.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(buf);
            byte[] md = md5.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ����ָ����ʽ������
     *
     * @param fmt
     * @return
     */
    public static String getTime(String fmt) {
        Date now = new Date();
        SimpleDateFormat f = new SimpleDateFormat(fmt);
        String s = f.format(now);
        return s;
    }

    /**
     * @author hxx
     * @date 2016.7.27
     * ����base64ΪͼƬ
     * @param path �ļ�·�������û�� /
     * @param time ʱ�䣬����·�������ʽ�� 2010-12-31 00:11:22
     * @param code ���ţ��������������
     * @param base ͼƬbase64����
     * @return
     * @throws Exception
     */
    public static String saveToImgFile(String path, String time, String code,
                                       String base) throws Exception {
        StringBuffer sb = new StringBuffer();
        StringBuffer str = new StringBuffer();
        sb.append(path);
        sb.append("/");
        sb.append(time.substring(0,4));
        sb.append(time.substring(5,7));
        sb.append(time.substring(8,10));
        sb.append("/");
        sb.append(time.substring(11,13));
        sb.append(time.substring(14,16));
        sb.append("/");
        sb.append(time.substring(17,19));
        sb.append(code);
        sb.append(".jpg");
        str.append(time.substring(0,4));
        str.append(time.substring(5,7));
        str.append(time.substring(8,10));
        str.append("/");
        str.append(time.substring(11,13));
        str.append(time.substring(14,16));
        str.append("/");
        str.append(time.substring(17,19));
        str.append(code);
        str.append(".jpg");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(base);
        FileOutputStream fo = new FileOutputStream(createFile(sb.toString()));
        fo.write(b);
        fo.close();
        return str.toString();
    }
    /*
     * ����base64ΪͼƬ
     * @param path �ļ�·�������û�� /
     * @param time ʱ�䣬����·�������ʽ�� 2010-12-31 00:11:22
     * @param code ���ţ��������������
     * @param base ͼƬbase64����
     * @return
     * @throws Exception
     */
    public static String saveImgFile(String path, String time, String code,
                                     String base) throws Exception {
        // get file name
        StringBuffer sb = new StringBuffer();
        sb.append(path);
        sb.append("/");
        sb.append(time.substring(0,4));
        sb.append(time.substring(5,7));
        sb.append(time.substring(8,10));
        sb.append("/");
        sb.append(time.substring(11,13));
        sb.append(time.substring(14,16));
        sb.append("/");
        sb.append(time.substring(17,19));
        sb.append(code);
        sb.append(".jpg");

        // decode
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(base);

        //save file
        FileOutputStream fo = new FileOutputStream(createFile(sb.toString()));
        fo.write(b);
        fo.close();

        return "";
    }

    /**
     * ͼƬ�ϴ�
     * @param path �ļ�·�������û��/
     * @param time ʱ�䣬��ʽΪ 2012-02-03 04:05:06
     * @param code ���룬13λ����
     * @return
     * @throws Exception
     */
    public static String saveUploadImg(String path, String time, String code,
                                       byte[] buf,int startPos, int endPos) throws Exception {
        // get file name
        StringBuffer sb = new StringBuffer();
        sb.append(path);
        sb.append("/");
        sb.append(time.substring(0,4));
        sb.append(time.substring(5,7));
        sb.append(time.substring(8,10));
        sb.append("/");
        sb.append(time.substring(11,13));
        sb.append(time.substring(14,16));
        sb.append("/");
        sb.append(time.substring(17,19));
        sb.append(code);
        sb.append(".jpg");

        // decode
        //BASE64Decoder decoder = new BASE64Decoder();
        //byte[] b = decoder.decodeBuffer(base);
        String res = "";
        if(new File(sb.toString()).exists()){
            res = "er";
        } else{
            //save file
            FileOutputStream fo = new FileOutputStream(createFile(sb.toString()));
            fo.write(buf,startPos,(endPos - startPos));
            fo.close();

            res = "ok";
        }
        return res;
    }

    /**
     * @param time ʱ�䣬����·�������ʽ�� 2010-12-31 00:11:22
     * @param code ���ţ��������������
     * @param base ͼƬbase64����
     * @return
     * @throws Exception
     */
    private static final String KEY = "SaCXe2duNp5tfpBTse9q";
    public static String saveImgFileEncryption (String path, String time, String code,
                                                String base) throws Exception {
        StringBuffer sb = new StringBuffer();
        StringBuffer str = new StringBuffer();
        sb.append(path);
        sb.append("/");
        sb.append(time.substring(0,4));
        sb.append(time.substring(5,7));
        sb.append(time.substring(8,10));
        sb.append("/");
        sb.append(time.substring(11,13));
        sb.append(time.substring(14,16));
        sb.append("/");
        sb.append(time.substring(17,19));
        sb.append(code);
        sb.append(".txt");

        byte[] b = RC4.rc4(KEY, base.getBytes());
        FileOutputStream fo = new FileOutputStream(createFile(sb.toString()));
        fo.write(b);
        fo.close();
        return str.toString();
    }

    /**
     * �����Ŀ¼�ļ�
     * @param path
     * @return
     */
    public static File createFile(String path) {
        File file = new File(path);
        File parent = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(File.separator)));
        if (!parent.exists()) {
            createFile(parent.getPath());
            parent.mkdirs();
        }
        return file;
    }

    public static String fmtNum(String sNum) {
        String res = sNum;
        if(sNum.length()>0){
            if(sNum.charAt(0)=='.'){
                res = "0".concat(res);
            }
        }
        return res;
    }
}
